package cn.yunxiang.summer.admin.web.service.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.mapper.MemberMapper;
import com.wzj.soopin.member.service.MemberRegisterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.yunxiang.summer.common.constant.Constants;
import cn.yunxiang.summer.common.constant.GlobalConstants;
import cn.yunxiang.summer.common.constant.SystemConstants;
import cn.yunxiang.summer.common.domain.model.LoginUser;
import cn.yunxiang.summer.common.domain.model.RegisterBody;
import cn.yunxiang.summer.common.domain.model.SmsLoginBody;
import cn.yunxiang.summer.common.enums.LoginType;
import cn.yunxiang.summer.common.enums.UserType;
import cn.yunxiang.summer.common.exception.user.CaptchaExpireException;
import cn.yunxiang.summer.common.exception.user.UserException;
import cn.yunxiang.summer.common.utils.MessageUtils;
import cn.yunxiang.summer.common.utils.StringUtils;
import cn.yunxiang.summer.common.utils.ValidatorUtils;
import cn.yunxiang.summer.common.json.utils.JsonUtils;
import cn.yunxiang.summer.common.redis.utils.RedisUtils;
import cn.yunxiang.summer.common.satoken.utils.LoginHelper;
import cn.yunxiang.summer.system.domain.SysUser;
import cn.yunxiang.summer.system.domain.vo.SysClientVo;
import cn.yunxiang.summer.system.domain.vo.SysUserVo;
import cn.yunxiang.summer.system.mapper.SysUserMapper;
import cn.yunxiang.summer.web.domain.vo.LoginVo;
import cn.yunxiang.summer.web.service.IAuthStrategy;
import cn.yunxiang.summer.web.service.SysLoginService;
import org.springframework.stereotype.Service;

/**
 * 短信认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("sms" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class SmsAuthStrategy implements IAuthStrategy {

    private final SysLoginService loginService;
    private final SysUserMapper userMapper;
    private final MemberMapper memberMapper;
    private final MemberRegisterService memberRegisterService;


    @Override
    public LoginVo login(String body, SysClientVo client) {
        SmsLoginBody loginBody = JsonUtils.parseObject(body, SmsLoginBody.class);
        ValidatorUtils.validate(loginBody);
        String tenantId = loginBody.getTenantId();
        String phonenumber = loginBody.getPhonenumber();
        String smsCode = loginBody.getSmsCode();
        LoginUser loginUser = checkUser(client, phonenumber, smsCode);
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginModel model = new SaLoginModel();
        model.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setUserId(loginUser.getUserId());
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        loginVo.setUserSig(loginUser.getUserSig());
        return loginVo;
    }


    private LoginUser checkUser(SysClientVo client, String phonenumber, String smsCode) {
        if("app".equals(client.getClientKey())){
            //会员登录
            Member member = loadMemberByPhonenumber(phonenumber);

            //手机号登录，如果没有则创建一个
            if (member == null) {
                RegisterBody registerBody = new RegisterBody();
                registerBody.setPhoneNumber(phonenumber);
                registerBody.setCode(smsCode);
                registerBody.setUserType(UserType.APP_USER.getUserType());
                registerBody.setClientId(client.getClientId());
                registerBody.setUuid(phonenumber);
                member = memberRegisterService.register(registerBody);
                return loginService.buildLoginUser(member);
            } else {
                loginService.checkLogin(LoginType.SMS, "tenantId", member.getUserName(), () -> !validateSmsCode("tenantId", phonenumber, smsCode));
                // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了


                LoginUser user=loginService.buildLoginUser(member);
                //检查member是否绑定了用户，如果有则获取用户信息
                if(ObjectUtil.isNotEmpty(member.getUserId())){
                    SysUserVo sysUser = userMapper.selectVoById(member.getUserId());
                    if(ObjectUtil.isNotEmpty(sysUser)){
                        user.setTenantId(sysUser.getTenantId());
                    }
                }
                // 获取会员绑定团长的租户id
                if(member.getSpreadUid() != null){
                    user.setReferenceTenantId(memberMapper.getReferenceTenantIdBySpreadUid(member.getSpreadUid()));
                }
                return user;
            }
        }else{
            //管理员登录
            SysUserVo user = loadUserByPhonenumber(phonenumber);
            loginService.checkLogin(LoginType.SMS, user.getTenantId(), user.getUserName(), () -> !validateSmsCode("tenantId", phonenumber, smsCode));

            // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
            return loginService.buildLoginUser(user);
        }
    }

    private void checkMemberLogin(){

    }

    /**
     * 校验短信验证码
     */
    private boolean validateSmsCode(String tenantId, String phonenumber, String smsCode) {
        String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + phonenumber);
        if (StringUtils.isBlank(code)) {
            loginService.recordLogininfor(tenantId, phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        return code.equals(smsCode);
    }

    private SysUserVo loadUserByPhonenumber(String phonenumber) {
        SysUserVo user = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, phonenumber));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", phonenumber);
            throw new UserException("user.not.exists", phonenumber);
        } else if (SystemConstants.DISABLE.equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", phonenumber);
            throw new UserException("user.blocked", phonenumber);
        }
        return user;
    }
    private Member loadMemberByPhonenumber(String phonenumber) {
        Member user = memberMapper.selectOne(new LambdaQueryWrapper<Member>().eq(Member::getPhoneHidden, phonenumber));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", phonenumber);
            return null;
        } else if (cn.yunxiang.summer.common.domain.event.Constants.MEMBER_ACCOUNT_STATUS.FORBIDDEN.equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", phonenumber);
            throw new UserException("user.blocked", phonenumber);
        } else if (cn.yunxiang.summer.common.domain.event.Constants.MEMBER_ACCOUNT_STATUS.REVOKED.equals(user.getStatus())) {
            log.warn("已注销的用户：{} 重新登录", phonenumber);
            memberMapper.updateById(Member.builder().id(user.getId()).status(cn.yunxiang.summer.common.domain.event.Constants.MEMBER_ACCOUNT_STATUS.NORMAL).build());
        }
        return user;
    }

}
